﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Mail;

namespace CNVP.Framework.Utils
{
    /// <summary>
    /// 邮件发送类
    /// </summary>
    /// <pre>例如：</pre>
    /// <pre>MailUtils _MailUtils = new MailUtils();</pre>
    /// <pre>_MailUtils.SmtpServer = "smtp.163.com";</pre>
    /// <pre>_MailUtils.UserName = "您的账号";</pre>
    /// <pre>_MailUtils.UserPass = "您的密码";</pre>
    /// <pre>_MailUtils.Send("接收人邮件地址","发件人邮件地址","邮件主题","邮件内容");</pre>
    public class MailUtils
    {
        /// <summary>
        /// 邮件服务器地址
        /// </summary>
        public string SmtpServer { get; set; }
        /// <summary>
        /// 邮件登录账号
        /// </summary>
        public string UserName { get; set; }
        /// <summary>
        /// 邮件登录密码
        /// </summary>
        public string UserPass { get; set; }
        /// <summary>
        /// 邮件发送
        /// </summary>
        /// <param name="To">接收人地址</param>
        /// <param name="From">发件人地址</param>
        /// <param name="Subject">邮件主题</param>
        /// <param name="Message">邮件内容</param>
        /// <returns>发送是否成功</returns>
        public bool Send(string To, string From, string Subject, string Message)
        {
            return Send(To, From, Subject, Message, false);
        }
        /// <summary>
        /// 邮件发送
        /// </summary>
        /// <param name="To">接收人地址</param>
        /// <param name="From">发件人地址</param>
        /// <param name="Subject">邮件主题</param>
        /// <param name="Message">邮件内容</param>
        /// <param name="isText">是否为文本</param>
        /// <returns>发送是否成功</returns>
        public bool Send(string To, string From, string Subject, string Message, Boolean isText)
        {
            try
            {
                System.Web.Mail.MailMessage mailMessage = new System.Web.Mail.MailMessage();
                mailMessage.To = To;
                mailMessage.From = From;
                mailMessage.Subject = Subject;
                mailMessage.Body = Message.Replace("\r\n", "<br>");
                mailMessage.BodyFormat = isText ? MailFormat.Text : MailFormat.Html;

                mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //基本验证
                mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", UserName); //设定用户名
                mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", UserPass); //设定密码

                SmtpMail.SmtpServer = SmtpServer;//设定SMTP服务器
                SmtpMail.Send(mailMessage);
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}